package com.xu.easyexcel.nio;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class TcpServer {

    public static void main(String[] args) throws Exception {

        TcpServer tcpServer = new TcpServer();
        tcpServer.start();

    }

    /*监听端口*/
    private final int port = 8888;
    private final String ipAddress = "localhost";

    /*缓冲区大小*/
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    /*其它相关定义*/
    Selector selector;
    ServerSocketChannel channel;
    ServerSocket socket;

    /*启动*/
    public void start() throws Exception {

        /*初始化一个Selector*/
        selector = Selector.open();

        /*打开通道*/
        channel = ServerSocketChannel.open();

        /*非阻塞模式*/
        channel.configureBlocking(false);

        /*本机IP*/
        InetAddress ip = InetAddress.getByName(ipAddress);
        //InetAddress ip = InetAddress.getLocalHost();
        System.out.println("ip地址是：" + ip.toString());
        /*绑定IP和端口*/
        InetSocketAddress address = new InetSocketAddress(ip, port);
        socket = channel.socket();
        socket.bind(address);
        /*启动监听*/
        System.out.println("TCP服务器开始监听...");
        listen();

    }

    /*停止*/
    public void stop() throws Exception {
        channel.close();
        selector.close();
    }

    /*监听*/
    public void listen() throws Exception {
        /*注册接收事件*/
        channel.register(selector, SelectionKey.OP_ACCEPT);
        /*无限循环*/
        while (true) {
            selector.select();
            /*轮询事件*/
            Iterator iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = (SelectionKey) iter.next();
                iter.remove();
                /*事件分类处理*/
                if (key.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    System.out.println("新终端已连接:" + sc.getRemoteAddress());
                } else if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    int recvCount = sc.read(buffer);
                    if (recvCount > 0) {
                        byte[] arr = buffer.array();
                        System.out.println(sc.getRemoteAddress() + "发来数据: " + new String(arr, "UTF-8"));
                        buffer.flip();
                    } else {
                        sc.close();
                    }
                    buffer.clear();
                } else {

                }
            }
        }
    }


}